<template>
  <div>
    <BasicTable @register="registerTable" size="small">
      <template #form-tm="{ model, field }">
        <a-radio-group
          v-model:value="choosetmType"
          style="margin: 0 5px 5px 0"
          button-style="solid"
          @change="changeChooseTm"
        >
          <a-radio-button value="1">本月</a-radio-button>
          <a-radio-button value="3">本季度</a-radio-button>
          <a-radio-button value="4">本年</a-radio-button>
          <a-radio-button value="5">自定义</a-radio-button>
        </a-radio-group>
        <a-range-picker
          v-show="choosetmType == '5'"
          v-model:value="model[field]"
          valueFormat="YYYY-MM-DD"
          :allowClear="false"
        />
      </template>
      <template #toolbar>
        <a-button type="primary" @click="onAddEduRecord"> 新增 </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditEduRecord.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteEduRecord.bind(null, record),
              },
            },
            {
              icon: 'ant-design:audit-outlined',
              label: '设置记录人员关联',
              color: 'success',
              onClick: onSetUsers.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddOrUpdateEduRecord @register="registerAddOrUpdateForm" @success="afterSuccess" />
    <SetEduRecordUser @register="registerUserTree" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, provide, nextTick, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import moment from 'moment';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { Tag } from 'ant-design-vue';

  //引入子组件
  import SetEduRecordUser from './SetEduRecordUser.vue';
  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  const { createMessage } = useMessage();
  import { queryEduRecord, deleteEduRecord } from '/@/api/ehs/eduRecord';
  import { queryEduRecordSchema, eduRecordColumns } from './edurecord.data';
  import { getUserOrganization } from '/@/api/ehs/organization';
  const { globalProjectCode } = useGlobSetting();
  import { queryEnumOptions } from '/@/api/platform/enum';
  import AddOrUpdateEduRecord from './AddOrUpdateEduRecord.vue';
  export default defineComponent({
    name: 'EduRecordIndex',
    components: { BasicTable, TableAction, Tag, AddOrUpdateEduRecord, SetEduRecordUser },
    setup() {
      const orgcode = ref('');
      const choosetmType = ref('4');
      const projectCode = ref<String>(globalProjectCode);
      const [registerAddOrUpdateForm, { openModal: openAddOrUpdateForm }] = useModal();
      const [registerUserTree, { openModal: openUserTree }] = useModal();
      const [registerTable, { reload, getForm }] = useTable({
        title: '安全培训记录管理',
        api: queryEduRecord,
        columns: eduRecordColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: false,
        bordered: true,
        canResize: true,
        striped: false,
        isTreeTable: true,
        actionColumn: {
          width: 230,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        useSearchForm: true,
        formConfig: {
          labelWidth: 100,
          schemas: queryEduRecordSchema,
        },
        immediate: false,
        pagination: false, //关闭分页,
        beforeFetch: (params) => {
          params.orgcode = orgcode.value;
          params.begintm = params.tm[0];
          params.endtm = params.tm[1];
          return params;
        },
      });

      function changeChooseTm(e) {
        let op = {
          1: [
            moment().startOf('month').format('YYYY-MM-DD'),
            moment().endOf('month').format('YYYY-MM-DD'),
          ],
          3: [
            moment().startOf('quarter').format('YYYY-MM-DD'),
            moment().endOf('quarter').format('YYYY-MM-DD'),
          ],
          4: [
            moment().startOf('year').format('YYYY-MM-DD'),
            moment().endOf('year').format('YYYY-MM-DD'),
          ],
        };
        if (e.target.value != '5') {
          getForm().setFieldsValue({
            tm: op[e.target.value],
          });
        }
        getForm().clearValidate();
      }

      /**
       * 删除
       */
      function onDeleteEduRecord(record: Recordable) {
        deleteEduRecord(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      function onAddEduRecord() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '安全培训记录',
          operateType: OperationTypeEnum.ADD,
          orgcode: orgcode.value,
        };
        openAddOrUpdateForm(true, propsData);
      }
      function onEditEduRecord(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '安全培训记录',
          operateType: OperationTypeEnum.EDIT,
          orgcode: orgcode.value,
          dataId: record.id,
        };
        openAddOrUpdateForm(true, propsData);
      }

      function onSetUsers(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '安全培训记录',
          operateString: '设置培训人员',
          orgcode: orgcode.value,
          dataId: record.id,
        };
        openUserTree(true, propsData);
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }

      onMounted(() => {
        getUserOrganization(projectCode.value).then((res) => {
          // 请求时需要传入用户的组织编码
          orgcode.value = res?.orgcode;
          reload();
        });
      });

      return {
        registerTable,
        afterSuccess,
        registerAddOrUpdateForm,
        onDeleteEduRecord,
        registerUserTree,
        onAddEduRecord,
        onEditEduRecord,
        onSetUsers,
        changeChooseTm,
        choosetmType,
      };
    },
  });
</script>
